package grame

import grails.converters.JSON
import grails.converters.XML
import org.apache.log4j.LogManager

/**
 * @author Shining Wang <shiningwang@topca.com>
 */
class LoggerController {

    static allowedMethods = [show: "GET", update: "POST", save: "POST"]

    def index() {}

    def show(String logger) {
        def _logger = LogManager.getLogger(logger)
        def result = [logger: _logger.name, level: _logger.level.toString()]
        log.trace("logger [" + result.logger + "] level is " + result.level)
        render result as JSON
    }

    def update() {
        def reqData = request.JSON;
        String logger = reqData?.logger ?: params.logger ?: grailsApplication.config['grails.project.groupId']
        String level = reqData?.level ?: params.level ?: 'INFO'
        log.trace("try to update logger [" + logger + "] to " + level)
        Log4jGrameUtil.setLoggerLevel(logger, level)

        def _logger = LogManager.getLogger(logger)
        def result = [logger: _logger.name, level: _logger.level.toString()]
        log.trace("logger [" + result.logger + "] has been updated to " + result.level)
        render result as JSON
    }

    def save() {
        Log4jGrameUtil.store()
        render "OK"
    }

    def test() {
        log.error("test error level")
        log.info("test info level")
        log.debug("test debug level")
        log.trace("test trace level")
        def result = [:]
        result.errorEnabled = log.errorEnabled
        result.debugEnabled = log.debugEnabled
        result.infoEnabled = log.infoEnabled
        result.traceEnabled = log.traceEnabled
        render result as JSON
    }

    def debugLog4jGrameUtil() {
        def reqData = request.JSON;
        Boolean isDebug = reqData?.isDebug ?: params.isDebug ?: null
        def result = [isDebug: isDebug]
        if (isDebug != null) {
            System.setProperty("grame.debug", String.valueOf(isDebug));
        } else {
            result.isDebug = Boolean.valueOf(System.getProperty("grame.debug", "false"))
        }
        withFormat {
            html { redirect(action: 'index') }
            json { render(result as JSON) }
            xml { render(result as XML) }
        }
    }

}

